package com.hxzy.controller.admin;

import com.hxzy.common.properties.CaptchaProperty;
import com.hxzy.common.vo.resp.R;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 功能描述 :验证码控制器
 *
 * @author tonneyyy
 */
@Api(tags = "后台管理-验证码")
@RestController
@RequestMapping(value = "/api/captcha")
public class CaptchaController {

    @Autowired
    private CaptchaProperty captchaProperty;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成验证码
     * @return
     */
    @ApiOperation(value = "验证码")
    @GetMapping
    public R<Object> captcha(){
        //验证码类型（png,gif,airth）
        Captcha  captcha=null;
        if(this.captchaProperty.getType().equals("png")){
            captcha= new SpecCaptcha();
        }else  if(this.captchaProperty.getType().equals("gif")){
            captcha= new GifCaptcha();
        }else {
            captcha= new ArithmeticCaptcha();
        }
        //为验证码赋值
        captcha.setWidth(this.captchaProperty.getWidth());
        captcha.setHeight(this.captchaProperty.getHeight());
        captcha.setLen(this.captchaProperty.getLen());
        //生成验证码
        String value= captcha.text();
        String image=captcha.toBase64();

        //存放验证码到redis中
        String uuid= UUID.randomUUID().toString();
        this.redisTemplate.opsForValue().set(this.captchaProperty.getRedisPrefix()+uuid,value,this.captchaProperty.getExpired(), TimeUnit.MINUTES);

        //发送给端
        Map<String,Object> map=new HashMap<>();
        map.put("uuid",uuid);
        map.put("image",image);

        return R.okHasData(map);

    }
}
